import json
from datetime import datetime, timedelta
import requests
from weixintuisong import tuisong,tuisong2
from weibo_comment import get_comment
from weibo_uinfo import get_uinfo
from utils import mongo_manager
weibo_user = mongo_manager(collect_name='weibo_user',db='cl_data')
weibo_blog = mongo_manager(collect_name='weibo_blog',db='cl_data')
weibo_comments = mongo_manager(collect_name='weibo_comments',db='cl_data')
def get_mymblog(page = 1):
    headers = {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "priority": "u=0, i",
        "sec-ch-ua": "\"Chromium\";v=\"130\", \"Google Chrome\";v=\"130\", \"Not?A_Brand\";v=\"99\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Linux\"",
        "sec-fetch-dest": "document",
        "sec-fetch-mode": "navigate",
        "sec-fetch-site": "same-origin",
        "sec-fetch-user": "?1",
        "upgrade-insecure-requests": "1",
        "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
    }
    cookies = {
        "SINAGLOBAL": "8051481509490.477.1725417483785",
        "SCF": "AiHhHpjpUWHWnw4SPlbn0Blpe01ucnX2MUzKWh0fqSb96uh2rN6GVyJBgMyb4CP0aWNA7WmWLcNlYlY8hYs04yo.",
        "ULV": "1730362247897:2:1:1:2795453509399.395.1730362247887:1725417483789",
        "ALF": "1733559052",
        "SUB": "_2A25KKAZcDeRhGeNJ6VIS-S7EzDWIHXVpRAeUrDV8PUJbkNAbLRjAkW1NS_5D5YxOEMatinDhQIKyoRGoJG2oLmN3",
        "SUBP": "0033WrSXqPxfM725Ws9jqgMF55529P9D9WhmxpO6_7Bbx4r5qcvFEF1M5JpX5KMhUgL.Fo-Neo501K5RS0.2dJLoI0qLxK-LBo5L12qLxK-LBo2L1h2LxK-LB-BLBK.LxKML1-2L1hBLxK-L1K5L12eLxKqLBK2L12et",
        "XSRF-TOKEN": "dON_EZE-rzC882UKUGWD1HKU",
        "PC_TOKEN": "41d5ffa4ab",
        "WBPSESS": "G9Ff9BQjWfN2Zb8Vj7-gc-yXFs3Y9sWM72U5flc0bOD_g3vusEwwgCVT1Zq8J4AHtyRQtKwyQ8ZeFytfBXqGKm3BVm3PZWC--9PF9kcRdgaCfdfWeuzv1nUrrjhQazTX_vzcTwqrGJgLvPogGQFHeA=="
    }
    url = "https://weibo.com/ajax/statuses/mymblog"
    params = {
        "uid": "3919603060",
        "page":page,
        "feature": "0"
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    print(response.url,response)

    # print(response.text)
    return response.json()['data']['list']

def save_uinfo():
    uinfo = get_uinfo()
    user = {}
    user['id'] = uinfo['id']
    user['screen_name'] = uinfo['screen_name']
    user['转评赞'] = uinfo['status_total_counter']['total_cnt']
    user['累计评论'] = uinfo['status_total_counter']['comment_cnt']
    user['累计转发'] = uinfo['status_total_counter']['repost_cnt']
    user['累计获赞'] = uinfo['status_total_counter']['like_cnt']
    user['认证'] = uinfo['verified_reason']
    user['描述'] = uinfo['description']
    user['粉丝量'] = uinfo['followers_count']
    user['关注量'] = uinfo['friends_count']
    timestamp_seconds = int(datetime.now().timestamp())
    user["_id"] = f"{uinfo['id']}_{timestamp_seconds}"
    user['时间戳'] = timestamp_seconds
    # 格式化当前时间为标准形式
    now = datetime.now()
    current_time = now.strftime("%Y%m%d %H:%M:%S")

    user['时间'] =current_time
    try:
        weibo_user.insertOne(user)
    except Exception as e:
        print(e)
def save_myblog():
    for page in range(1,3):
        mymblog = get_mymblog(page=page)
        for blog in mymblog:
            reslut = {}
            reslut['_id'] = blog['id']  # created_at
            reslut['uid'] = blog['user']['id']
            # 原始时间字符串
            time_str = blog['created_at']
            # 解析时间字符串
            dt = datetime.strptime(time_str, "%a %b %d %H:%M:%S %z %Y")
            # 格式化为所需格式
            formatted_time = dt.strftime("%Y%m%d %H:%M")
            reslut['time'] = formatted_time
            reslut['text_raw'] = blog['text_raw'] if blog['text_raw'] != '转发微博' else '转发微博：' + blog['retweeted_status'][
                'text_raw']
            try:
                weibo_blog.insertOne(reslut)
            except Exception as e:
                print(e)

def save_comments(reslut):
    max_id =0
    params = {
        "flow": "1",  # 按时间
        "is_reload": "1",
        "id": reslut['_id'],
        "is_show_bulletin": "2",
        "is_mix": "0",
        "count": "20",
        'max_id': max_id,
        "uid": reslut['uid'],
        "fetch_level": "0",
        "locale": "zh"
    }
    while True:
        comments = get_comment(params=params)
        params['max_id'] = comments['max_id'] if 'max_id' in comments else 0
        print (reslut['_id'],params['max_id'])
        if params['max_id'] == 0:
            break
        for comment in comments['data']:
            for comment2 in comment['comments']: # 保存二级评论
                reslut2 = {}
                reslut2["_id"] = comment2['id']
                # if weibo_comments.findOne({'_id': comment2['id']}):
                #     continue
                reslut2["评论type"] ='二级评论'
                reslut2['微博id'] = reslut['_id']
                reslut2["微博原文"] = reslut['text_raw']
                reslut2["一级评论文本"] =  comment['text_raw']
                reslut2["来源"] = comment2['source']
                reslut2["评论用户"] = comment2['user']['screen_name']
                time_str = comment2['created_at']
                # 解析时间字符串
                dt = datetime.strptime(time_str, "%a %b %d %H:%M:%S %z %Y")
                # 格式化为所需格式
                formatted_time = dt.strftime("%Y%m%d %H:%M")
                reslut2['time'] = formatted_time
                reslut2["评论序号"] = comment2['floor_number']
                reslut2["二级评论文本"] = comment2['text_raw']
                reslut2["点赞量"] = comment2['like_counts']
                try:
                    weibo_comments.insertOne(reslut2)
                except Exception as e:
                    weibo_comments.updateOne({"_id":reslut2['_id']},reslut2)
            reslut1 = {}
            reslut1["_id"] = comment['id']  #
            # if weibo_comments.findOne({"_id": comment['id']}):
            #     continue
            reslut1["评论type"] = '一级评论'
            reslut1['微博id'] = reslut['_id']
            reslut1["微博原文"] = reslut['text_raw']
            reslut1["一级评论文本"] = comment['text_raw']
            reslut1["来源"] = comment['source']
            reslut1["评论用户"] = comment['user']['screen_name']
            time_str = comment['created_at']
            # 解析时间字符串
            dt = datetime.strptime(time_str, "%a %b %d %H:%M:%S %z %Y")
            # 格式化为所需格式
            formatted_time = dt.strftime("%Y%m%d %H:%M")
            reslut1['time'] = formatted_time
            reslut1["评论序号"] = comment['floor_number']
            reslut1["点赞量"] = comment['like_counts']
            reslut1["回复量"] = comment['total_number']
            try:
                weibo_comments.insertOne(reslut1)
            except Exception as e:
                weibo_comments.updateOne({"_id":reslut1["_id"]},reslut1)

def save_main():
    save_uinfo()
    save_myblog()
    # 获取当前日期
    current_date = datetime.now()
    # 计算60天前的日期
    sixty_days_ago = current_date - timedelta(days=60)
    # 执行查询，查找 'time' 字段大于 'sixty_days_ago' 的文档
    seeds = weibo_blog.findAll({"time": {"$gt": sixty_days_ago}})
    for seed in seeds:
        save_comments(seed)
        weibo_blog.updateOne({'_id':seed['_id']},{'status_comment':'done'})
        # break

def tuisong_main():
    timestamp_seconds = int(datetime.now().timestamp())  # 当前时间戳
    # 计算往前一小时的时间
    now = datetime.now()
    one_day_ago = now - timedelta(days=1)
    # 格式化时间
    one_day_ago = one_day_ago.strftime("%Y%m%d %H:%M:%S")
    # 用户
    seed = weibo_user.findOne({'时间戳': {'$gt': timestamp_seconds- 3600}})
    data ={}
    data['用户'] ={}
    if seed:
        data['用户'] = seed
    #微博
    data['微博'] = []
    seeds = weibo_blog.findAll({'status_send':None})
    for seed in seeds:
        data['微博'].append(seed)
        weibo_blog.updateOne({'_id':seed['_id']},{'status_send':'done'})
    # # 评论
    data['评论'] = []
    seed = weibo_comments.findAll({'status_send': None, 'time': {'$gt': one_day_ago}}).limit(5)
    for s in seed:
        res = {}
        res['评论type'] =s['评论type']
        if s['评论type'] == '二级评论':
            res['二级评论'] = s['二级评论文本']
        res['微博原文'] = s['微博原文']
        res['一级评论文本'] = s['一级评论文本']
        res['点赞数'] = s['点赞数']
        res['时间'] = s['time']
        # tuisong(json.dumps(res,ensure_ascii=False))
        data['评论'].append(res)
        weibo_comments.updateOne({'_id':s['_id']},{'status_send':'done'})
    # print(len(str(data)))
    tuisong2(data =data)
    while True:
        datas =[]
        num =0
        seed = weibo_comments.findAll({'status_send': None, 'time': {'$gt': one_day_ago}}).limit(5)
        for s in seed:
            res = {}
            res['评论type'] = s['评论type']
            if s['评论type'] == '二级评论':
                res['二级评论'] = s['二级评论文本']
            res['微博原文'] = s['微博原文']
            res['一级评论文本'] = s['一级评论文本']
            res['点赞数'] = s['点赞数']
            res['时间'] = s['time']
            datas.append(res)
            num+=1
            weibo_comments.updateOne({'_id': s['_id']}, {'status_send': 'done'})
        tuisong(text=json.dumps(datas, ensure_ascii=False))
        if num <=5:
            break
if __name__ == "__main__":
    print()
    save_main()
